<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="测试名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入测试名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="测试时间" prop="testDate">
        <el-date-picker v-model="queryParams.testDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择测试时间" clearable>
        </el-date-picker>
      </el-form-item>
      <el-form-item label="得分" prop="score">
        <el-input v-model="queryParams.score" placeholder="请输入得分" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['ex:test_bank:add']">开始自测</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['ex:test_bank:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="test_bankList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="测试名称" align="center" prop="name">
        <template slot-scope="scope">
          <router-link :to="'/ex/test_bank-do_test/index/' + scope.row.id" class="link-type">
            <span>{{ scope.row.name }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="测试时间" align="center" prop="testDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.testDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="beginTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总题数" align="center" prop="total"/>
      <el-table-column label="对题数" align="center" prop="right"/>
      <el-table-column label="得分" align="center" prop="score"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==0" type="danger" effect="plain" size="mini">测试中</el-tag>
          <el-tag v-else type="success" effect="plain" size="mini">已结束</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['ex:test_bank:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改自测题库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="mini">
        <el-form-item label="测试名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入测试名称" style="width: 260px"/>
        </el-form-item>
        <el-form-item label="选题策略" prop="sig">
          <el-radio v-model="form.sig" label="ratio">按题库比例</el-radio>
          <el-radio v-model="form.sig" label="average">平均选择</el-radio>
          <el-radio v-model="form.sig" label="optional">自选</el-radio>
        </el-form-item>
        <el-form-item label="题目数量" prop="total" v-if="form.sig !== 'optional'">
          <el-input-number size="small" :min="0" v-model="form.total" controls-position="right"/>
        </el-form-item>
        <div class="customer-table">
          <el-table v-loading="loading" ref="questionTable" :data="questionBank.list" height="355" width="100%" @selection-change="handleQuestionChange"
                    :show-header="false" size="small">
            <el-table-column type="selection" width="45"/>
            <el-table-column width="400">
              <template slot-scope="scope">
               {{scope.row.name}}({{scope.row.total}})
              </template>
            </el-table-column>
            <el-table-column>
              <template slot-scope="scope" v-if="form.sig === 'optional' && scope.isSelected">
                <div>
                  <el-input-number size="small" :min="0" :max="scope.row.total" @change="changeInput"
                                   v-model="scope.row.number" controls-position="right"></el-input-number>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listTest_bank, getTest_bank, delTest_bank, addTest_bank, updateTest_bank} from "@/api/ex/test_bank";
import {listQuestion_bank,} from "@/api/ex/question_bank";


export default {
  name: "Test_bank",
  data() {
    return {
      prefix :'key_',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 自测题库表格数据
      test_bankList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        testDate: null,
        score: null,
      },
      // 表单参数
      form: {
        sig:'ratio',
        questionCheckeds:{},
        total: 100,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" }
        ],
        total: [
          { required: true, message: "请输入数量", trigger: "blur" }
        ]
      },
      //题库列表
      questionBank:{
        list:[],
        total:0,
        checkeds:[],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询题库列表 */
    getBankList() {
      this.loading = true;
      listQuestion_bank({pageNum:1,pageSize:1000}).then(response => {
        this.questionBank.list = response.rows;
        this.loading = false;
      });
    },
    /** 查询自测题库列表 */
    getList() {
      this.loading = true;
      listTest_bank(this.queryParams).then(response => {
        this.test_bankList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sig:'ratio',
        questionCheckeds:{},
        id: null,
        userId: null,
        name: null,
        testDate: null,
        beginTime: null,
        endTime: null,
        total: 100,
        right: null,
        questionIds: null,
        answerList: null,
        score: null,
        status: null,
        reservedOne: null,
        reservedTwo: null,
        createTime: null
      };
      this.$nextTick(() => {
        this.$refs.questionTable.clearSelection();
      });
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleQuestionChange(selection){
      this.form.questionCheckeds = {};
      this.questionBank.total = 0;
      this.questionBank.checkeds = [];
      //初始化
      this.questionBank.list.forEach(item=>{
        item.isChecked = false;
      })
      selection.forEach(item => {
        // this.form.questionCheckeds[this.prefix + item.id] = 0; //[{id:1,number:12}]
        item.isChecked = true;
        this.questionBank.total += item.total;
        this.questionBank.checkeds.push(item);
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "创建理论测试";
    },
    // /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.reset();
    //   const id = row.id || this.ids
    //   getTest_bank(id).then(response => {
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "修改自测题库";
    //   });
    // },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.questionBank.checkeds.length<=0){this.$modal.msgWarning("请选择基础题库");return;}
          if (this.form.sig != 'optional'){
            if (this.form.total == 0){this.$modal.msgWarning("题目数量不可为0");return;}
            if (this.questionBank.total < this.form.total){this.$modal.msgWarning("题目数量超过了题库总数");return;}
            if (this.form.sig == 'average'){
              var half = this.form.total % 2 == 0 ? this.form.total / 2 : this.form.total / 2 +1;
              var pass = false;
              this.questionBank.checkeds.forEach( item =>{
                if (item.total < half){
                  pass = true;return;
                }
              })
              if(pass){
                this.$modal.msgWarning("超出题库数量");return;
              }
            }
          }
          var count = 0;
          var checkeds = {};
          this.questionBank.list.forEach( item =>{
            if(item.isChecked){
              if (isNaN(item.number)){
                count += 0;
                checkeds[item.id] = 0;
              }else{
                count += item.number;
                checkeds[item.id] = item.number;
              }
            }
          })
          if(this.form.sig == 'optional'){
            if (count == 0){this.$modal.msgWarning("题目数量不可为0");return;}
          }
          this.form.questionCheckeds = checkeds;
          //执行
          addTest_bank(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
            //跳转
            this.$router.push({
              name: 'Test',
              params: {
                testBankId:response.bean.id,
              }
            })
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除自测题库编号为"' + ids + '"的数据项？').then(function () {
        return delTest_bank(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ex/test_bank/export', {
        ...this.queryParams
      }, `test_bank_${new Date().getTime()}.xlsx`)
    },
    /** 手动渲染 */
    changeInput(){
      this.$forceUpdate()
    },
  },
  watch:{
    'open':function (n,o) {
      if (n) this.getBankList();
    }
  }
};
</script>
<style>
.customer-table{
  border-style: solid;
  border-color: silver;
  border-width: 1px;
  margin-left: 15px;
  width: 620px;
  height: 360px;
}
.el-table__row>td{
  border: none;
}
.el-table::before {
  height: 0px;
}
</style>
